package com.pls.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;







import com.pls.actionObjects.SearchRequest;
import com.pls.actionObjects.SearchResponse;
import com.pls.actionObjects.ValidateLoginRequest;
import com.pls.actionObjects.ValidateLoginResponse;
import com.pls.constants.GenericConstants;
import com.pls.constants.SearchTypeEnum;
import com.pls.constants.ValidationErrorEnum;
import com.pls.dao.DAOFactory;
import com.pls.dao.EmployeeDAO;
import com.pls.dao.UserDAO;
import com.pls.domain.Employee;
import com.pls.domain.EmployeeWorkstation;
import com.pls.domain.ExceptionError;
import com.pls.domain.ValidationError;


public class ValidateLoginHandler extends BaseRequestHandler<ValidateLoginResponse, ValidateLoginRequest>{
	
	Logger logger = Logger.getLogger(ValidateLoginHandler.class);
	
	public ValidateLoginHandler(Class<ValidateLoginResponse> tResponse) {
		super(tResponse);
		// TODO Auto-generated constructor stub
	}
	
	protected ArrayList<ValidationError> validate(
			ValidateLoginRequest request) {
		ArrayList<ValidationError> errors = new ArrayList<ValidationError>();
		ValidationError valError;
		if (request == null) {
			valError = new ValidationError();
			valError.setMessage("Request is null.");
			valError.setErrorName(ValidationErrorEnum.NullRequest);
			errors.add(valError);
			return errors;
		}

		return errors;
	}
	
	
	
	protected ValidateLoginResponse process(ValidateLoginRequest request) {

		ValidateLoginResponse response = new ValidateLoginResponse();
		// call data layer
		EmployeeWorkstation employeeWorkstation = new EmployeeWorkstation();
		UserDAO userDAO = DAOFactory.getUserDAO();
	

		
		try {
			logger.debug("Process for ValidateLogin entered.");
			// validate login through google
			if(request.getLoginType().equalsIgnoreCase(GenericConstants.GOOGLE_LOGIN_TYPE)){
				employeeWorkstation = userDAO.userLoginByGoogle(request.getEmailAddress());		
			}
			//validate login normally
			else{
				employeeWorkstation = userDAO.userLoginByCredentials(request.getEmailAddress(), request.getPassword());
				
			}
			

			//set the response

			response.setEmployeeWorkstation(employeeWorkstation);
			


		} catch (SQLException e) {
			// ADD LOGGER
			ExceptionError sqlError = new ExceptionError(e.getClass()
					.toString(),
					"Sorry, an SQL error occurred while accessing the DB.");
			response.setExceptionError(sqlError);
			logger.error("SQLException :" + e.getMessage());
		} catch (Exception e) {
			ExceptionError sqlError = new ExceptionError(e.getClass()
					.toString(),
					"Sorry, an error occurred while accessing the DB.");
			response.setExceptionError(sqlError);
			logger.error("Exception :" + e.getMessage());
		}
		
		logger.debug(this.getClass() + "- process method exited.");
		return response;
	}

}
